package com.roc.web.action.terminal;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TPosInfo;
import com.roc.service.IMerchantServices;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;


@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/ysbTermSnRepAgent")
public class YsbTermSnRepAgentAction  extends PaginationBaseAction {

	private static final long serialVersionUID = 1L;

	private Logger logger = LogManager.getLogger(YsbTermSnRepAgentAction.class);

	private YsbTermSnRepAgentSearchCondition searchCondition;
	private TPosInfo tPos;
	private String tid;
	private String mid;
	private String serialNumer;
	private String posBrandCode;// 厂商编号
	private String posModelNo;// 厂商型号
	private String message;// 返回信息
	
	private String invaild;// 失效标志
	
	@Autowired
	IorgService orgService;

	@Autowired
	IPageService pagenitionService;

	@Autowired
	ITerminalService terminalService;

	@Autowired
	IMerchantServices merchantServices;
	
	@Autowired
	IPowerInfoService powerInfoService;
	/**
	 * 终端绑定初始化
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/terminal/ysbTermSnRepAgentList.jsp") })
	public String init() throws Exception {
		Operators loginOperator = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		Map<String, String> map = powerInfoService.queryRealIdByOpId(loginOperator.getSuperiorId(), loginOperator.getRoleType(), loginOperator.getId(), loginOperator.getOrgCode());
        String superRole= map.get("superRole");
		if( !loginOperator.getRoleType().equals( Role.SYSTEM.getCode() )  
				&& !( loginOperator.getRoleType().equals( Role.OPERATORS_COMM.getCode() ) && superRole.equals( Role.SYSTEM.getCode() ) ) ) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		org();
		searchCondition = new YsbTermSnRepAgentSearchCondition();
		searchCondition.setTid(tid);
		searchCondition.setMid(mid);
		try {
			TPosInfo bean = new TPosInfo();
			bean.setMercCode(mid);
			bean.setTermCode(tid);
			String agentId = terminalService.queryYsbDirAgentByTerm(bean);
			searchCondition.setAgentId(agentId);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return SUCCESS;
	}
	/**
	 * 初始化参数
	 */
	private void org() throws Exception {
		try {
			getRequest().setAttribute("brandMap",ConfigProperties.getYsbBrandProperties());
			getRequest().setAttribute("nameMap", new ArrayList<Map<String,Object>>());
			getRequest().setAttribute("typeMap", ConfigProperties.getSysDB1("Terminal_Type",true));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 查询待换机的SN序列号
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "ysbTermSnRepAgentList", results = { @Result(name = "success", location = "/pages/terminal/ysbTermSnRepAgentList.jsp") })
	public String ysbTermSnRepAgentList() throws Exception {
		Operators loginOperator = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);

		if (searchCondition == null) {
			searchCondition = (YsbTermSnRepAgentSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new YsbTermSnRepAgentSearchCondition();
			}
		}
		Map<String, String> map = powerInfoService.queryRealIdByOpId(loginOperator.getSuperiorId(), loginOperator.getRoleType(), loginOperator.getId(), loginOperator.getOrgCode());
        String superRole= map.get("superRole");
		if( !loginOperator.getRoleType().equals( Role.SYSTEM.getCode() )  
				&& !( loginOperator.getRoleType().equals( Role.OPERATORS_COMM.getCode() ) && superRole.equals( Role.SYSTEM.getCode() ) ) ) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		if (Constance.isEmpty(mid) || Constance.isEmpty(tid) || Constance.isEmpty(searchCondition.getAgentId())) {
			invaild = "error";
			return SUCCESS;
		}
		try {
			org();
			int rows = pagenitionService.countSQL(searchCondition);
			List<TPosInfo> posList = new ArrayList<TPosInfo>();
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);//
				if (searchRsList != null && searchRsList.size() > 0) {
					TPosInfo pos = null;
					Iterator iterator = searchRsList.iterator();
					BigDecimal value = null;
					while (iterator.hasNext()) {
						Object[] obj = (Object[]) iterator.next();
						pos = new TPosInfo();
						pos.setSerialNum(Constance.Null2EmptyTrim(obj[0]));

						pos.setPosBrand(ConfigMerinfoUtil.getPosBRAND(Constance
								.Null2EmptyTrim(obj[1])));
						pos.setPosType(ConfigMerinfoUtil.getPosType(Constance
								.Null2EmptyTrim(obj[2])));
						pos.setPosName(ConfigMerinfoUtil.getPosMODEL(
								Constance.Null2EmptyTrim(obj[3]),
								Constance.Null2EmptyTrim(obj[1])));

						value = (BigDecimal) obj[4];
						pos.setAgentId(value.longValue());
						pos.setIsUsed(convertConstantValue(Constance
								.Null2EmptyTrim(obj[5])));
						pos.setDtCreate((Date) obj[6]);
						pos.setDtLostmod((Date) obj[7]);
						// 厂商编号
						pos.setPosBrandCode(Constance.Null2EmptyTrim(obj[1]));
						// 型号编号
						pos.setPosBrandName(Constance.Null2EmptyTrim(obj[3]));
						posList.add(pos);
					}
				}
			}
			searchRsList.clear();
			searchRsList.addAll(posList);
			dealWithTheListSpecially(searchRsList);
			getRequest().setAttribute("posList", posList);
			getRequest().setAttribute("selModelCode",
					searchCondition.getPosName());
			getRequest().setAttribute("oldBandCode",
					searchCondition.getPosBrand());
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);

		} catch (ServiceException e) {

			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());

		}
		return SUCCESS;
	}

	/**
	 * 终端绑定操作
	 * 
	 * @return
	 */
	@Action(value = "ysbTermSnRepAgentSelect", results = { @Result(name = "success", type = "json") })
	public String ysbTermSnRepAgentSelect() {
		Operators loginOperator = (Operators) ActionContext.getContext()
				.getSession().get(Constant.SESSION_LOGIN_MERCHANT);		
		try {
			if (Constance.isEmpty(mid) || Constance.isEmpty(tid)
					|| Constance.isEmpty(serialNumer)
					|| Constance.isEmpty(posBrandCode)
					|| Constance.isEmpty(posModelNo)) {
				invaild = "error";
				return SUCCESS;
			}
			TPosInfo bean = new TPosInfo();
			bean.setMercCode(mid);
			bean.setTermCode(tid);
			String dirAgentId = terminalService.queryYsbDirAgentByTerm(bean);
			message = terminalService.replaceYsbTerminal(serialNumer, posBrandCode, posModelNo, mid, tid,dirAgentId, loginOperator);
			
		} catch (ServiceException e) {
			message = "云商宝终端换机出错！";
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 转换Y/N枚举字段为中文汉字枚举值
	 * 
	 * @param value
	 * @return
	 */
	private String convertConstantValue(String value) {
		String constantValue = "";
		if (value != null && !"".equals(value)) {
			if (value.equals("Y")) {
				constantValue = "是";
			} else if (value.equals("N")) {
				constantValue = "否";
			}
		}
		return constantValue;
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSession()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (YsbTermSnRepAgentSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_YSB_TERM_SN_REP_AGENT);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc
	 * .page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc
	 * .page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_YSB_TERM_SN_REP_AGENT,
				searchCondition);
	}

	public YsbTermSnRepAgentSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(YsbTermSnRepAgentSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public String getTid() {
		return tid;
	}

	public void setTid(String tid) {
		this.tid = tid;
	}

	public String getMid() {
		return mid;
	}

	public void setMid(String mid) {
		this.mid = mid;
	}

	public String getSerialNumer() {
		return serialNumer;
	}

	public void setSerialNumer(String serialNumer) {
		this.serialNumer = serialNumer;
	}
	
	public String getPosBrandCode() {
		return posBrandCode;
	}

	public void setPosBrandCode(String posBrandCode) {
		this.posBrandCode = posBrandCode;
	}

	public String getInvaild() {
		return invaild;
	}

	public void setInvaild(String invaild) {
		this.invaild = invaild;
	}
	public TPosInfo gettPos() {
		return tPos;
	}
	public void settPos(TPosInfo tPos) {
		this.tPos = tPos;
	}
	public String getPosModelNo() {
		return posModelNo;
	}
	public void setPosModelNo(String posModelNo) {
		this.posModelNo = posModelNo;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	


}
